package parser;
import java.io.*;
import antlr.RecognitionException;

public class Disassembler {
    

    public Disassembler() {
    }
    
    String name(int name) {
        return NameTable.names.get(name);
    }
    
    public void disassembleCode(byte[] bytes, PrintStream out) {
        int index = 0;
        while (index < bytes.length) {
            int op = bytes[index];
            out.print("" + index + ":  \t" + Opcodes.names[op]);
//            int args = Opcodes.args[op];
            int args = 0; // FIX THIS
            if (op == Opcodes.LOAD_ATTR || op == Opcodes.STORE_ATTR || 
                op == Opcodes.LOAD_GLOBAL || op == Opcodes.STORE_GLOBAL ||
                op == Opcodes.LOAD_LOCAL || op == Opcodes.STORE_LOCAL) {
                int name = (bytes[index+1] << 8) + (bytes[index+2] & 0xff);
                out.println(" " + name(name));
            } else {
                if (args == 0) {
                    out.println();
                } else if (args == 1) { 
                    out.println(" " + bytes[index+1]);
                } else if (args == 2) {
                    out.println(" " + bytes[index+1] + " " + bytes[index+2]);
                } else if (args == 3) {
                    int name = (bytes[index+1] << 8) + (bytes[index+2] & 0xff);
                    out.println(" " + name(name) + " " + bytes[index+3]);
                } else {
                    throw new Error("Too many arguments");
                }
            }
            index += args + 1;
        }        
    }

    public void dumpCode(Stmt s, PrintStream out) throws RecognitionException {
        ByteStream stream = new ByteStream();
        s.write(stream);
        byte[] bytes = stream.toByteArray();
        disassembleCode(bytes, out);
    }

}


